import json
import logging
import os

from xToolkit import xfile

from tool.utils import write_as_excel, read_columns_list_from_file
from tool.utils_config import get_access_token_from_config
from tool.utils_net import is_token_valid, request_get


def get_org_repo_url_list(organization, renew_now=False):
    org_repos_stat_file = init_repo_info_excel(organization, renew_now)
    repo_url_list = read_repos_url_list_from_stat_file(org_repos_stat_file)
    return repo_url_list


def get_org_repo_name_list(organization, renew_now=False):
    org_repos_stat_file = init_repo_info_excel(organization, renew_now)
    repo_url_list = read_repos_name_list_from_stat_file(org_repos_stat_file)
    return repo_url_list


def init_repo_info_excel(organization, renew_now=False, org_repos_stat_file=None):
    if not org_repos_stat_file:
        org_repos_stat_file = organization + '_组织仓库清单.xlsx'
    if renew_now or not os.path.exists(org_repos_stat_file):
        generate_repos_info_excel_for_org(organization, org_repos_stat_file)
    return org_repos_stat_file


def read_repos_url_list_from_stat_file(org_repos_stat_file):
    return read_columns_list_from_file(org_repos_stat_file, '仓库链接')


def read_repos_name_list_from_stat_file(org_repos_stat_file):
    return read_columns_list_from_file(org_repos_stat_file, '仓库名称')


def generate_repos_info_excel_for_org(organization, output_file_name):
    print(f'正在尝试获取组织{organization}的仓库清单...')
    repos_info_list = []
    repos_list = get_repos_list_for_org(organization)
    for repo in repos_list:
        process_repo_info_and_load_into_list(repo, repos_info_list)
    columns_order = ['仓库名称', '仓库链接', '仓库描述', '仓库状态', '创建时间']
    write_as_excel(output_file_name, repos_info_list, columns_order)
    return output_file_name


def get_repos_list_for_org(organization):
    url_list = form_api_list_need_to_request(organization)
    repos_list = get_response_list_from_url(url_list)
    assert repos_list, f'目前识别输入的组织名为：{organization}请输入有效的组织名，例如：openharmony'
    return repos_list


def process_repo_info_and_load_into_list(repo, repos_info_list):
    name = repo['name']
    link = 'https://gitee.com/' + repo['full_name']
    logging.debug(link)
    desc = repo['description']
    status = repo['status']
    created_at = repo['created_at']
    repos_info_list.append(
        {"仓库名称": name, "仓库链接": link, "仓库描述": desc, "仓库状态": status, '创建时间': created_at})


def form_api_list_need_to_request(organization, max_pro_page=100):
    api_list = []
    access_token = get_access_token_from_config()
    assert is_token_valid(access_token), '请于config.toml, 配置有效的access_token'
    request_url = "https://gitee.com/api/v5/orgs/{}/repos?access_token={}&type=all&per_page=100&page={}"
    for page_num in range(1, max_pro_page):
        api_url = request_url.format(organization, access_token, page_num)
        api_list.append(api_url)
    return api_list


def get_response_list_from_url(url_list):
    response_list = []
    for request_url in url_list:
        json_response = get_json_response_from_url(request_url)
        if not json_response:
            break
        response_list.extend(json_response)
    return response_list


def get_json_response_from_url(request_url):
    response = request_get(request_url, timeout=100)
    json_obj_list = json.loads(response.text)
    if 'message' in json_obj_list:
        logging.error('访问url出错：' + request_url)
        logging.error('错误信息如下：' + json_obj_list['message'])
    if type(json_obj_list) == list and len(json_obj_list) > 0:
        return json_obj_list
    return []


if __name__ == '__main__':
    pass
